package com.medicinezp.webapi;

import com.medicinezp.baseconfig.domain.*;
import com.medicinezp.baseconfig.service.*;
import com.medicinezp.common.config.AliConfig;
import com.medicinezp.common.config.MedicinezpConfig;
import com.medicinezp.common.core.controller.BaseController;
import com.medicinezp.common.core.domain.AjaxResult;
import com.medicinezp.common.core.domain.entity.SysUser;
import com.medicinezp.common.core.domain.model.LoginUser;
import com.medicinezp.common.core.page.TableDataInfo;
import com.medicinezp.common.core.redis.RedisCache;
import com.medicinezp.common.utils.DateUtils;
import com.medicinezp.common.utils.DictUtils;
import com.medicinezp.common.utils.SecurityUtils;
import com.medicinezp.common.utils.file.FileUploadUtils;
import com.medicinezp.common.utils.file.FileUtils;
import com.medicinezp.system.service.ISysConfigService;
import com.medicinezp.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 不需要授权接口
 *
 * @author waoqi
 * @date 2021-08-18
 */
@RestController
@RequestMapping("/api/noAuth")
public class AuthFreeController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AuthFreeController.class);

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IBaseTextContentService baseTextContentService;

    @Autowired
    private IBaseRangeConfigService baseRangeConfigService;

    @Autowired
    private IBaseJobCategoryService baseJobCategoryService;

    @Autowired
    private IBaseJobTypeService baseJobTypeService;

    @Autowired
    private IBaseBannerService bannerService;


    @Autowired
    private IBaseArticleService articleService;

    @Autowired
    private IBaseRegionProvinceService baseRegionProvinceService;


    @Autowired
    private IBaseIndustryService baseIndustryService;

    @Autowired
    private IBaseCompanyService baseCompanyService;

    @Autowired
    private IBaseJobsService baseJobsService;

    @Autowired
    private IBaseCompanyService companyService;

    @Autowired
    private IBaseCompanyAddressService companyAddressService;

    @Autowired
    private IBaseCompanyPhotoService companyPhotoService;

    @Autowired
    private IBaseUserIntentionService baseUserIntentionService;
    @Autowired
    private IBaseAdvertisingService baseAdvertisingService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IBaseUserBrowserService baseUserBrowserService;

    @Autowired
    private IBaseUserCollectService baseUserCollectService;

    @Autowired
    private IBaseUserJobApplyService baseUserJobApplyService;


    @GetMapping("/queryJobFilterData")
    public AjaxResult queryJobFilterData() {
        List resultData = new ArrayList<>();
        Map education = new HashMap();
        education.put("code", "education");
        education.put("name", "学历要求");
        education.put("data", DictUtils.getDictCache("sys_education"));
        resultData.add(education);

        Map salary = new HashMap();
        salary.put("code", "salary");
        salary.put("name", "薪资待遇");
        List rangeList = redisCache.getCacheList("rangeListKey");
        if(rangeList!=null && rangeList.size()==0){
            rangeList = baseRangeConfigService.selectBaseRangeConfigList(new BaseRangeConfig());
            redisCache.setCacheList("rangeListKey",rangeList);
        }
        salary.put("data", rangeList);
        resultData.add(salary);

        Map experience = new HashMap();
        experience.put("code", "experience");
        experience.put("name", "经验要求");
        experience.put("data", DictUtils.getDictCache("sys_work_experience"));
        resultData.add(experience);


        Map jobCategroy = new HashMap();
        jobCategroy.put("code", "jobCategory");
        jobCategroy.put("name", "职位类型");
        List jobTypeList = redisCache.getCacheList("jobTypeListKey");
        if(jobTypeList!=null && jobTypeList.size()==0){
            jobTypeList = baseJobCategoryService.selectBaseJobCategoryList(new BaseJobCategory());
            redisCache.setCacheList("jobTypeListKey",jobTypeList);
        }
        jobCategroy.put("data", jobTypeList);
        resultData.add(jobCategroy);
        return AjaxResult.success(resultData);
    }

    @GetMapping("/queryCompanyFilterData")
    public AjaxResult queryCompanyFilterData() {
        List resultData = new ArrayList<>();

        Map scale = new HashMap();
        scale.put("code", "scale");
        scale.put("name", "公司规模");
        scale.put("data", DictUtils.getDictCache("sys_company_large_scale"));
        resultData.add(scale);

        Map jobCategroy = new HashMap();
        jobCategroy.put("code", "industry");
        jobCategroy.put("name", "主营行业");
        List industryList = redisCache.getCacheList("industryListKey");
        if(industryList!=null && industryList.size()==0){
            industryList = baseIndustryService.selectBaseIndustryList(new BaseIndustry());
            redisCache.setCacheList("industryListKey",industryList);
        }
        jobCategroy.put("data", industryList);
        resultData.add(jobCategroy);
        return AjaxResult.success(resultData);
    }

    @GetMapping("/queryIndustryData")
    public AjaxResult queryIndustryData(BaseIndustry industry) {
        industry.setAvailableFlag("Y");
        List<BaseIndustry> industryList = baseIndustryService.selectBaseIndustryList(industry);
        return AjaxResult.success(industryList);
    }

    @GetMapping("/queryIndustryDetail")
    public AjaxResult queryIndustryData(@RequestParam(value = "id", required = true) Long id) {
        BaseIndustry industry = baseIndustryService.selectBaseIndustryById(id);
        List<BaseCompany> brenchCompany = baseCompanyService.selectBrenchCompanyList(id);
        BaseCompany param = new BaseCompany();
        param.setIndustry(industry.getName());
        param.setAvailableFlag("Y");
        //List<BaseCompany> listCompany = baseCompanyService.selectBaseCompanyList(param);
        //brenchCompany.addAll(listCompany);
        industry.setCompanyList(brenchCompany);
        return AjaxResult.success(industry);
    }

    //查询岗位类型
    @GetMapping("/queryJobTypeData")
    public AjaxResult queryJobTypeData() {
        List<BaseJobCategory> firstType = baseJobCategoryService.selectBaseJobCategoryList(new BaseJobCategory());
        List<BaseJobType> secondType = baseJobTypeService.selectJobTypeListByCategroy(new BaseJobType());
        firstType.stream().forEach(type -> {
            List<BaseJobType> secondList = secondType.stream().filter(t -> t.getCategoryId().intValue() == type.getCategoryId().intValue()).collect(Collectors.toList());
            type.setChildList(secondList);
        });
        return AjaxResult.success(firstType);
    }

    //查询岗位类型
    @GetMapping("/queryJobTypeDetail")
    public AjaxResult queryJobTypeDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseJobType secondType = baseJobTypeService.selectBaseJobTypeById(id);
        Long userId = -1L;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        BaseUserCollect collect = new BaseUserCollect();
        collect.setUserId(userId);
        collect.setCollectId(id);
        collect.setType("03");
        List<BaseUserCollect> collectList = baseUserCollectService.selectBaseUserCollectList(collect);
        if (collectList.size() > 0) {
            secondType.setCollectFlag(true);
        } else {
            secondType.setCollectFlag(false);
        }
        return AjaxResult.success(secondType);
    }

    //查询岗位类型
    @GetMapping("/queryJobDataByType")
    public TableDataInfo queryJobDataByType(BaseJobs jobParam) {
        jobParam.setStatus("02");
        jobParam.setTypeId(jobParam.getTypeId());
        startPage();
        List<BaseJobs> jobList = baseJobsService.selectJobsData(jobParam);
        return getDataTable(jobList);
    }

    //查询岗位详情
    @GetMapping("/queryJobDataDetail")
    public AjaxResult queryJobDataDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseJobs jobDetail = baseJobsService.selectBaseJobsById(id);

        Long userId = -1L;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        BaseUserBrowser param = new BaseUserBrowser();
        param.setUserId(userId);
        param.setJobId(id);
        List<BaseUserBrowser> list = baseUserBrowserService.selectBaseUserBrowserList(param);
        if (list.size() == 0) {
            param.setCreateTime(DateUtils.getNowDate());
            int result = baseUserBrowserService.insertBaseUserBrowser(param);
        }

        BaseUserCollect collect = new BaseUserCollect();
        collect.setCollectId(id);
        collect.setUserId(userId);
        collect.setType("01");
        List<BaseUserCollect> collectList = baseUserCollectService.selectBaseUserCollectList(collect);
        if (collectList.size() > 0) {
            jobDetail.setCollectFlag(true);
        } else {
            jobDetail.setCollectFlag(false);
        }
        return AjaxResult.success(jobDetail);
    }

    @ApiOperation("获取协议文本内容")
    @GetMapping("/getProtocolDetail")
    public AjaxResult getProtocolDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseTextContent text = baseTextContentService.selectBaseTextContentById(id);
        return AjaxResult.success(text);
    }

    /**
     * 求职资讯列表
     *
     * @param article
     * @return
     */
    @GetMapping("/getJobArticleList")
    public TableDataInfo getJobArticle(BaseArticle article) {
        article.setShowFlag("Y");
        List<BaseArticle> articles = articleService.selectBaseArticleList(article);
        articles.stream().forEach(art->{
            art.setTypeName(DictUtils.getDictLabel("base_article_type",art.getType()));
        });
        return getDataTable(articles);
    }


    /**
     * 求职资讯详情
     *
     * @param id 资讯ID
     * @return
     */
    @GetMapping("/getJobArticleInfo")
    public AjaxResult getJobArticleInfo(@RequestParam(value = "id", required = true) Long id) {
        BaseArticle article = articleService.selectBaseArticleById(id);
        article.setTypeName(DictUtils.getDictLabel("base_article_type",article.getType()));
        return AjaxResult.success(article);
    }

    /**
     * 查询轮播图列表
     *
     * @return
     */
    @GetMapping("/getBannerList")
    public AjaxResult getList() {
        BaseBanner banner = new BaseBanner();
        List<BaseBanner> banners = bannerService.selectBaseBannerList(banner);
        return AjaxResult.success(banners);
    }

    /**
     * 查询广告
     *
     * @return
     */
    @GetMapping("/getAdvertisingList")
    public AjaxResult getAdvertisingList() {
        BaseAdvertising param = new BaseAdvertising();
        param.setStatus("Y");
        List<BaseAdvertising> dataList = baseAdvertisingService.selectBaseAdvertisingList(param);
        return AjaxResult.success(dataList);
    }

    @ApiOperation("获取省份城市")
    @GetMapping("/getAllProvince")
    public AjaxResult getAllProvince() {
        List<BaseRegionProvince> list = baseRegionProvinceService.selectBaseRegionProvinceData(new BaseRegionProvince());
        return AjaxResult.success(list);
    }


    @PostMapping("/getCompanyList")
    public TableDataInfo getCompanyList(@RequestBody BaseCompany company) {
        startPage();
        company.setAuditStatus("02");
        List<BaseCompany> companyList = companyService.selectCompanyDataList(company);
        return getDataTable(companyList);
    }

    /**
     * 、
     * 查询公司详情
     *
     * @param id
     * @return
     */
    @GetMapping("/getCompanyDetail")
    public AjaxResult getCompanyInfo(@RequestParam(value = "id", required = true) Long id) {
        AjaxResult result = AjaxResult.success();
        BaseCompany company = companyService.selectBaseCompanyById(id);

        BaseCompanyAddress param = new BaseCompanyAddress();
        param.setCompanyId(id);
        List<BaseCompanyAddress> addressList = companyAddressService.selectBaseCompanyAddressList(param);
        company.setAddressList(addressList);

        BaseCompanyPhoto photoparam = new BaseCompanyPhoto();
        photoparam.setCompanyId(id);
        List<BaseCompanyPhoto> photoList = companyPhotoService.selectBaseCompanyPhotoList(photoparam);
        company.setPhotoList(photoList);

        if (company == null) {
            return AjaxResult.error("公司不存在");
        }

        BaseJobs job = new BaseJobs();
        //正常状态
        job.setStatus("02");
        job.setCompanyId(company.getId());
        List<BaseJobs> jobs = baseJobsService.selectBaseJobsList(job);
        result.put("jobData", jobs);
        result.put("jobNum", jobs.size());

        Long userId = -1L;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        if(userId.intValue()!=-1) {
            BaseUserCollect collect = new BaseUserCollect();
            collect.setUserId(userId);
            collect.setCollectId(id);
            collect.setType("02");
            List<BaseUserCollect> collectList = baseUserCollectService.selectBaseUserCollectList(collect);
            if (collectList.size() > 0) {
                company.setCollectFlag(true);
            } else {
                company.setCollectFlag(false);
            }
        }
        result.put("data", company);
        return result;
    }

    @GetMapping("/getCompanyJobList")
    public TableDataInfo getCompanyJobList(BaseJobs job) {
        //正常状态
        job.setStatus("02");
        startPage();
        List<BaseJobs> jobs = baseJobsService.selectBaseJobsList(job);
        return getDataTable(jobs);
    }

    @PostMapping("/getJobListData")
    public TableDataInfo getJobListData(@RequestBody BaseJobs jobVo) {
        BaseUserIntention intention = baseUserIntentionService.selectBaseUserIntentionById(jobVo.getIntentionId());
        if (intention != null) {
            jobVo.setCityName(intention.getWorkCity());
            jobVo.setTypeId(intention.getTypeId());
        }
        //正常状态
        jobVo.setStatus("02");
        startPage();
        List<BaseJobs> jobs = baseJobsService.selectQueryJobsList(jobVo);
        return getDataTable(jobs);
    }

    @GetMapping("/getJobDetail")
    public AjaxResult getJobDetail(@RequestParam(value = "id", required = true) Long id) {
        BaseJobs jobs = baseJobsService.selectBaseJobsById(id);
        BaseCompanyAddress address= companyAddressService.selectBaseCompanyAddressById(jobs.getAddrId());
        jobs.setCompanyAddress(address);
        Long userId = -1L;
        try {
            userId = SecurityUtils.getLoginUser().getUser().getUserId();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        if(userId.intValue()!=-1) {
            BaseUserBrowser param = new BaseUserBrowser();
            param.setUserId(userId);
            param.setJobId(id);
            List<BaseUserBrowser> list = baseUserBrowserService.selectBaseUserBrowserList(param);
            if (list.size() == 0) {
                param.setCreateTime(DateUtils.getNowDate());
                int result = baseUserBrowserService.insertBaseUserBrowser(param);
            }
            BaseUserCollect collect = new BaseUserCollect();
            collect.setUserId(userId);
            collect.setCollectId(id);
            collect.setType("01");
            List<BaseUserCollect> collectList = baseUserCollectService.selectBaseUserCollectList(collect);
            if (collectList.size() > 0) {
                jobs.setCollectFlag(true);
            } else {
                jobs.setCollectFlag(false);
            }

            BaseUserJobApply apply = new BaseUserJobApply();
            apply.setUserId(userId);
            apply.setJobId(id);
            List<BaseUserJobApply> jobApply = baseUserJobApplyService.selectBaseUserJobApplyList(apply);
            jobs.setApplyFlag(false);
            if (jobApply.size() > 0) {
                jobs.setApplyFlag(true);
            }
        }
        return AjaxResult.success(jobs);
    }


    @GetMapping("/getNewJobList")
    public TableDataInfo getNewJobList(@RequestParam(value = "cityName", required = true) String cityName) {
        //正常状态
        BaseJobs param = new BaseJobs();
        param.setCityName(cityName);
        param.setStatus("02");
        startPage();
        List<BaseJobs> jobs = baseJobsService.selectQueryNewJobsList(param);
        return getDataTable(jobs);
    }

    @GetMapping("/getRelationPhone")
    public AjaxResult getRelationPhone() {

        String businessPhone = configService.selectConfigByKey("sys.bussiness.concact.phone");
        String relationPhone = configService.selectConfigByKey("sys.bussiness.relationus.phone");
        AjaxResult result = AjaxResult.success();
        result.put("businessPhone", businessPhone);
        result.put("relationPhone", relationPhone);
        return result;
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = MedicinezpConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = AliConfig.getImgPrefix() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("fileSize", file.getSize());
            ajax.put("fileName", url);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("/queryBrenchmarkCompany")
    public TableDataInfo queryBrenchmarkCompany(BaseCompany company) {
        startPage();
        List<BaseCompany> list = baseCompanyService.selectBrenchmarkCompanyList(company);
        return getDataTable(list);
    }

}
